package com.yj.auto.core.web.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.yj.auto.Constants;
import com.yj.auto.core.base.annotation.Controller;
import com.yj.auto.core.base.annotation.Valid;
import com.yj.auto.core.base.model.QueryModel;
import com.yj.auto.core.base.model.ResponseModel;
import com.yj.auto.core.jfinal.base.BaseController;
import com.yj.auto.core.web.system.model.Resource;
import com.yj.auto.core.web.system.model.Role;
import com.yj.auto.core.web.system.model.RoleResource;
import com.yj.auto.core.web.system.service.ResourceService;
import com.yj.auto.core.web.system.service.RoleService;
import com.yj.auto.helper.AutoHelper;
import com.yj.auto.plugin.table.model.DataTables;
import com.yj.auto.plugin.ztree.ZTreeNode;

/**
 * 系统角色 管理 描述：
 * 
 */
@Controller(viewPath = "system")
public class RoleController extends BaseController {
	private static final Log logger = Log.getLog(RoleController.class);

	private static final String RESOURCE_URI = "role/index";
	private static final String INDEX_PAGE = "role_index.html";
	private static final String FORM_PAGE = "role_form.html";

	RoleService roleSrv = null;
	ResourceService resourceSrv = null;

	public void index() {
		render(INDEX_PAGE);
	}

	public void list(QueryModel query) {
		DataTables<Role> dt = getDataTable(query, roleSrv);
		renderJson(dt);
	}

	public void resources(Integer roleId) {
		List<RoleResource> rrList = null;
		if (null != roleId) {
			Role role = roleSrv.getCache(roleId);
			if (null != role) {
				rrList = role.getResources();
			}
		}
		List<Resource> list = AutoHelper.getResourceService().getCaches();
		List<Map> result = new ArrayList<Map>();
		for (Resource c : list) {
			Map t = new HashMap();
			t.put("id", c.getId());
			t.put("pId", c.getParentId());
			t.put("name", c.getName());
			t.put("open", true);
			Map<String, Object> attributes = new HashMap<String, Object>();
			attributes.put("auths", c.getAuths());

			List<String> authChecked = new ArrayList<String>();
			if (null != rrList) {
				for (RoleResource rr : rrList) {
					if (c.getId().equals(rr.getResId())) {
						t.put("checked", true);
						if (StrKit.notBlank(rr.getResCode())) {
							authChecked.add(rr.getResCode());
						}
					}
				}
			}
			attributes.put("authChecked", authChecked);
			t.put("attributes", attributes);
			result.add(t);
		}
		this.setAttr("resources", JSON.toJSONString(result));
	}

	public void get() {
		form();
	}

	public void form() {
		Integer id = getParaToInt(0);
		Role model = null;
		if (null != id && 0 != id) {
			model = roleSrv.get(id);
		} else {
			model = new Role();
			model.setSort(Constants.MODEL_SORT_DEFAULT);
		}
		setAttr("model", model);
		this.resources(id);
		render(FORM_PAGE);
	}

	@Valid(type = Role.class)
	public boolean saveOrUpdate(Role model) {
		List<RoleResource> resources = new ArrayList<RoleResource>();
		String[] items = getParaValues("res_item");
		if (null != items) {
			for (String s : items) {
				String[] ss = s.split(";");
				RoleResource rr = new RoleResource();
				rr.setResId(Integer.parseInt(ss[0]));
				if (ss.length > 1)
					rr.setResCode(ss[1]);
				resources.add(rr);
			}
		}
		model.setResources(resources);
		model.setLuser(getSuId());
		model.setLtime(Constants.NOW());
		boolean success = false;
		if (null == model.getId()) {
			if (null != roleSrv.getByCode(model.getCode())) {
				ResponseModel<String> res = new ResponseModel<String>(false);
				res.setMsg("角色编号[" + model.getCode() + "]已存在!");
				renderJson(res);
				return false;
			}
			success = roleSrv.save(model);
		} else {
			success = roleSrv.update(model);
		}
		ResponseModel<String> res = renderSaveOrUpdate(success, roleSrv);
		return res.isSuccess();
	}

	public boolean delete() {
		ResponseModel<String> res = _delete(roleSrv);
		return res.isSuccess();
	}

	// public void menus() {
	// Integer id = getParaToInt("id");
	// Integer roleId = getParaToInt("roleId");
	// List<RoleResource> rrList = null;
	// if (null != roleId) {
	// Role role = roleSrv.getCache(roleId);
	// if (null != role) {
	// rrList = role.getResources();
	// }
	// }
	// List<Resource> list = resourceSrv.children(id,
	// Constants.DATA_STATE_VALID);
	// List<ZTreeNode> result = new ArrayList<ZTreeNode>();
	// for (Resource c : list) {
	// List<Resource> subs = resourceSrv.children(c.getId(),
	// Constants.DATA_STATE_VALID);
	// ZTreeNode t = getZTreeNode(c, subs.size() > 0, rrList);
	// t.setOpen(true);
	// for (Resource s : subs) {
	// ZTreeNode ch = getZTreeNode(s, resourceSrv.children(s.getId(),
	// Constants.DATA_STATE_VALID).size() > 0, rrList);
	// t.addChildren(ch);
	// }
	// result.add(t);
	// }
	// renderJson(result);
	// }
	//
	// private ZTreeNode getZTreeNode(Resource c, boolean parent,
	// List<RoleResource> rrList) {
	// ZTreeNode t = new ZTreeNode(c.getId().toString(), c.getName());
	// t.setIsParent(parent);
	// t.addAttribute("auths", c.getAuths());
	// List<String> authChecked = new ArrayList<String>();
	// if (null != rrList) {
	// for (RoleResource rr : rrList) {
	// if (c.getId().equals(rr.getResId())) {
	// t.setChecked(true);
	// if (StrKit.notBlank(rr.getResCode())) {
	// authChecked.add(rr.getResCode());
	// }
	// }
	// }
	// }
	// t.addAttribute("authChecked", authChecked);
	// return t;
	// }

}